/**
 * @file main.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2024-01-23
 *
 * @copyright Copyright (c) 2024
 *
*/
#include <FreeRTOS.h>
#include "task.h"
#include "queue.h"
#include "board.h"
#include "bluetooth.h"
#include "btble_lib_api.h"
#include "bl616_glb.h"
#include "rfparam_adapter.h"
#include "bflb_mtd.h"
// #include "easyflash.h"
#include "wifi_event.h"
#include "log.h"
#include "aiio_os_port.h"
#include "homeAssistantMQTT.h"
#include "voice_uart.h"
#include "bflb_uart.h"

#define DBG_TAG "MAIN"

struct bflb_device_s* uart1;
uart_rx_cmd_t uart_cmd;
static char uart_buff[5] = { 0 };

static const uart_data_t g_uart_buf[] = {
  {{0xA1, 0x00, 0x00, 0x00, 0xFF}, 5}, //wakeup_uni
  {{0xA1, 0x00, 0x01, 0x01, 0xFF}, 5}, //openL
  {{0xA1, 0x00, 0x01, 0x00, 0xFF}, 5}, //closeL
};

static bool switch_state;

void send_device_state_task(void){

    while (1)
    {
        ha_sw_entity_t* switch_cur = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "switch1");
        if(switch_cur!=NULL && switch_cur->switch_state!=switch_state){
            switch_cur->switch_state = switch_state;
            int ret = homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, switch_cur, switch_cur->switch_state);
            if (ret!=-1)LOG_I("%s send entity suceess,state=%s", switch_cur->name, switch_cur->switch_state?"true\n":"flase\n");
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
    
}

void ha_event_cb(ha_event_t event, homeAssisatnt_device_t* ha_dev)
{            
    LOG_I("ha_event_cb");
    switch (event)
    {
        case HA_EVENT_MQTT_CONNECED:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_CONNECED");
            
            //一定要加static
            static ha_sw_entity_t entity_sw1 = {
                    .name = "开关1",
                    .icon = "mdi:power",
                    .unique_id = "switch1",
            };

            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_SWITCH, &entity_sw1);
            homeAssistant_device_send_status(HOMEASSISTANT_STATUS_ONLINE);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, &entity_sw1, 0);

            xTaskCreate(send_device_state_task, (char *)"send_state", 1024, NULL, 26, NULL);
            break;
        case HA_EVENT_MQTT_DISCONNECT:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_DISCONNECT");

            break;
        case HA_EVENT_MQTT_COMMAND_SWITCH:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_SWITCH");
            // LOG_I("switch addr =%p", ha_dev->entity_switch->command_switch);
            LOG_I(" switch %s is %s", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"true":"flase");
            int ret = homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, ha_dev->entity_switch->command_switch, ha_dev->entity_switch->command_switch->switch_state);
            if (ret!=-1)LOG_I("%s send entity suceess,state=%s", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"true":"flase");
            break;
        default:
            break;
    }
}

static int voice_cmd_check(char* buff, int len)
{

    int data_cnt = 0, j = 0;
    // char* uart_txbuf = pvPortMalloc(4);
    // memset(uart_txbuf, 0, 4);
    while (1) {
        for (size_t i = 0; i < 5; i++)
        {
            if (buff[i]==g_uart_buf[j].data[i]) data_cnt++;
            else break;
        }
        if (data_cnt==g_uart_buf->len) break;
        data_cnt = 0;
        j++;
        if (j>23) return -1;
    }
    LOG_I("check uart cmd=%d", j);
    return j;
}

static void uart_isr(int irq, void* arg)
{ 
    LOG_I("uart_isr");
    uint32_t intstatus = bflb_uart_get_intstatus(uart1);
    if (intstatus & UART_INTSTS_RTO) {
        LOG_I("rx rto\r\n");
        memset(uart_buff, 0, 5);
        int index = 0;
        while (bflb_uart_rxavailable(uart1)) {
            // LOG_I("0x%02x\r\n", bflb_uart_getchar(uart1));
            uart_buff[index++] =  bflb_uart_getchar(uart1);
        }
         LOG_I("uart recv:%02X %02X %02X %02X %02X", uart_buff[0], uart_buff[1], uart_buff[2], uart_buff[3], uart_buff[4]);

        uart_cmd = voice_cmd_check(uart_buff, 5);

        switch (uart_cmd)
        {
            case UART_RX_CMD_OPENL:
            {
                LOG_I("Open");
                switch_state = true;
            }
            break;
            case UART_RX_CMD_CLOSEL:
            {
                LOG_I("Close");
                switch_state = false;
            }
            break;
            default:
                break;
        }
        uart_cmd = UART_RX_CMD_NONE;
        bflb_uart_int_clear(uart1, UART_INTCLR_RTO);
        LOG_I("Voice cmd: bflb_uart_int_clear\n");
    }
}

int main(void)
{

    board_init();
    bflb_mtd_init();
    // easyflash_init();
    // aiio_log_init();

    if (0 != rfparam_init(0, NULL, 0)) {
        LOG_E("PHY RF init failed!\r\n");
        return 0;
    }

    struct bflb_device_s* gpio = bflb_device_get_by_name("gpio");
    uart1 = bflb_device_get_by_name("uart1");
    struct bflb_uart_config_s cfg = {
        .baudrate = 115200,
        .data_bits = UART_DATA_BITS_8,
        .stop_bits = UART_STOP_BITS_1,
        .parity = UART_PARITY_NONE,
        .flow_ctrl = 0,
        .tx_fifo_threshold = 5,
        .rx_fifo_threshold = 5,
    };
    bflb_gpio_uart_init(gpio, GPIO_PIN_25, GPIO_UART_FUNC_UART1_TX);
    bflb_gpio_uart_init(gpio, GPIO_PIN_26, GPIO_UART_FUNC_UART1_RX);

    bflb_uart_init(uart1, &cfg);
    bflb_uart_rxint_mask(uart1, false);
    bflb_irq_attach(uart1->irq_num, uart_isr, NULL);
    bflb_irq_enable(uart1->irq_num);

    staWiFiInit();
    // homeassistant_blufi_init();

    static homeAssisatnt_device_t ha_device = {
        .mqtt_info.mqtt_host = "192.168.50.40",
        .mqtt_info.port = 1883,
        .mqtt_info.mqtt_username = "admin",
        .mqtt_info.mqtt_password = "Wang900213#",
        .name = "Ai-M6X-Voice",
        .model = "Ai-M6x-12F",
        .manufacturer = "Ai-Thinker",
        .hw_version = "v1.0",
        .sw_version = "v1.0.0",
    };
    homeAssistant_device_init(&ha_device, ha_event_cb);

    vTaskStartScheduler();

    while (1) {
        LOG_F("HomeAssistant free heap size=%d", aiio_os_get_free_heap_size());
        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}
